package com.example.a16478095zxl;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

import androidx.annotation.Nullable;

import java.util.List;

public class CompassActivity extends Activity implements SensorEventListener {
    private CompassView compassView;
    private boolean mRegisteredSensor;
    //定义SensorManager
    private SensorManager mSensorManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        compassView = new CompassView(this);
        setContentView(compassView);

        mRegisteredSensor = false;
        //取得SensorManager实例
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);

        if (sensors.size() > 0)
        {
            Sensor sensor = sensors.get(0);
            //注册SensorManager
            //this->接收sensor的实例
            //接收传感器类型的列表
            //接受的频率
            mRegisteredSensor = mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    @Override
    protected void onPause() {
        if (mRegisteredSensor)
        {
            //如果调用了registerListener
            //这里我们需要unregisterListener来卸载/取消注册
            mSensorManager.unregisterListener(this);
            mRegisteredSensor = false;
        }
        super.onPause();

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        // 接受方向感应器的类型
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION)
        {
            // 这里我们可以得到数据，然后根据需要来处理
            float x = sensorEvent.values[SensorManager.DATA_X];

            compassView.setDegree(x);

        }
    }
}
